package com.hs.telepass.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.hs.teleform.R;
import com.hs.telepass.Constants;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.controller.task.SendAuthTask;
import com.hs.telepass.controller.task.UpdateSessionTask;
import com.hs.telepass.dao.SingouProfilesDatabase;
import com.hs.telepass.dao.TelepassProfilesDatabase;
import com.hs.telepass.manager.PreferencesManager;
import com.hs.telepass.manager.ProfilesManager;
import com.hs.telepass.manager.SingouManager;
import com.hs.telepass.manager.TeleformManager;
import com.hs.telepass.model.Profile;
import com.hs.telepass.model.QrCodeModal;
import com.hs.telepass.model.SingouProfiles;
import com.hs.telepass.model.TelepassProfiles;
import com.hs.telepass.model.RepositoryProfile;
import com.hs.telepass.utils.ShortSoundUtil;
import com.hs.telepass.utils.StringUtil;
import com.hs.telepass.utils.ToastUtil;

import java.util.List;

/**
 * @author szw
 * @modified edvard
 * @time 2014-10-2
 */
public class InputUserInfoActivity extends BaseActivity {

    /**
     * 两个id写成相同的了，已经修改
     */
    @InjectView(R.id.edtText_username)
    EditText mEdtTextUsername;
    @InjectView(R.id.edtText_password)
    EditText mEdtTextPassword;
    @InjectView(R.id.button_commit)
    Button mButtonCommit;
    @InjectView(R.id.txtview_hostname)
    TextView mTxtviewHostname;
    @InjectView(R.id.cb_remember_password)
    CheckBox mSwitchLogin;
    @InjectView(R.id.btn_cancel)
    Button mBtnCancel;

    private Context mContext;
    private PreferencesManager mPreferencesManager;
    private ProfilesManager mProfilesManager;

    private QrCodeModal mCurrentQr;
    private RepositoryProfile mCurrentProfile;
    private List<SingouProfiles> mCurrentSingouList;
    private List<TelepassProfiles> mCurrentTelepassList;
    private Profile mProfile;
    private String mQrSessionId;
    private String mPublicKey;
    private String mRuntime_key;
    private String mHostname;
    private String mPathname;

    private String mQrId;
    private String mSid;

    /**
     * 判断来源于singou 还是 teleform
     */
    private int mSource;

    /**
     * 判讀是否來自科學館，如果來自科學館，則不用向數據庫保存密碼
     */
    private boolean isFromScience = false;


    @OnClick(R.id.button_commit)
    void commit() {
        String username = mEdtTextUsername.getText().toString();
        String password = mEdtTextPassword.getText().toString();
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            ToastUtil.showMessageInShort(mContext, R.string.input_commit_empty);
        } else {


            if (isFromSingou()) {

               /* if (!isSingouVerified()) {
                    ToastUtil.showMessageInShort(mContext, R.string.tip_security_profile_fail);
                    return;
                }*/

                try {
                    SingouManager.getInstance().sendAuth(mSid, username, password, mQrId, mRuntime_key);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                try {
                    if (!StringUtil.isEmpty(mRuntime_key) && !StringUtil.isEmpty(mPublicKey))
                        TeleformManager.getInstance().updateSession(mQrSessionId, username, password, mPublicKey, mRuntime_key);
                    else
                        ToastUtil.showMessageInShort(context, getString(R.string.pubkey_empty_tip));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }

    }

    @OnClick(R.id.btn_cancel)
    void backClick() {
        finish();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.input_info_activity);
        ButterKnife.inject(this);

        mContext = InputUserInfoActivity.this;
        mPreferencesManager = PreferencesManager.getInstance();
        mProfilesManager = ProfilesManager.getInstance();

        mSource = getIntent().getIntExtra(CaptureFragment.EXTRA_QRCODE_SOURCE, -1);
        mCurrentSingouList = mProfilesManager.getSingouProfilesList();
        mCurrentTelepassList = mProfilesManager.getTelepassProfilesList();

        Bundle bundle = getIntent().getBundleExtra(CaptureFragment.EXTRA_QRCODE_RESULT);
        if (!isFromSingou()) {
            mProfile = (Profile) bundle.getSerializable(CaptureFragment.BUNDLE_KEY_PROFILE);
            mQrSessionId = bundle.getString(CaptureFragment.BUNDLE_KEY_SESSIONID);
            mRuntime_key = bundle.getString(CaptureFragment.BUNDLE_KEY_RUNTIME_KEY);
            mPublicKey = bundle.getString(CaptureFragment.BUNDLE_KEY_PUBKEY);
            mPathname = bundle.getString(CaptureFragment.BUNDLE_PATH_NAME);
            mHostname = bundle.getString(CaptureFragment.BUNDLE_KEY_URL);
            //判斷是否來自科學館
            mHostname = scienceHall(mHostname);
            mTxtviewHostname.setText(mHostname);
        } else {
            mCurrentQr = (QrCodeModal) bundle.getSerializable(CaptureFragment.BUNDLE_KEY_QR);
            mProfile = (Profile) bundle.getSerializable(CaptureFragment.BUNDLE_KEY_PROFILE);
            mQrId = mCurrentQr.getI();
            mSid = bundle.getString(CaptureFragment.BUNDLE_KEY_SID);
            mRuntime_key = bundle.getString(CaptureFragment.BUNDLE_KEY_RUNTIME_KEY);
            mCurrentProfile = mCurrentQr.getProfile();
            if (null != mCurrentProfile)
                mTxtviewHostname.setText(mCurrentProfile.getTitle());
        }

        if (isFromSingou())
            mSwitchLogin.setChecked(mPreferencesManager.getSingouLoginSwitch());
        else
            mSwitchLogin.setChecked(mPreferencesManager.getTelepassLoginSwitch());

//        initViews();
        initUserProfileEditText();
        setListeners();
    }

    private void setListeners() {
        mSwitchLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isFromSingou())
                    mPreferencesManager.setSingouLoginSwitch(isChecked);
                else
                    mPreferencesManager.setTelepassLoginSwitch(isChecked);
            }
        });
    }


    private void initUserProfileEditText() {
        String lastUserName = "";
        String lastPassword = "";
        if (null != mProfile) {
            lastUserName = mProfile.getUsername();
            lastPassword = mProfile.getPassword();
        }

        mEdtTextUsername.setText(lastUserName);
        mEdtTextPassword.setText(lastPassword);
    }

    @Override
    public IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UpdateSessionTask.ACTION_UPDATE_SESSION_TASK);
        intentFilter.addAction(SendAuthTask.ACTION_SEND_AUTH_TASK);
        return intentFilter;
    }

    @Override
    public void handleOnReceive(Intent intent) {
        String action = intent.getAction();
        if (UpdateSessionTask.ACTION_UPDATE_SESSION_TASK.equals(action)) {
            handleUpdateSession(intent);
        } else if (SendAuthTask.ACTION_SEND_AUTH_TASK.equals(action)) {
            handleSendAuth(intent);
        }

    }

    private void handleUpdateSession(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                TelepassProfiles telepassProfiles = new TelepassProfiles();
                telepassProfiles.setHost(mHostname);
                telepassProfiles.setUsername(mEdtTextUsername.getText().toString());

                if (true == mPreferencesManager.getTelepassLoginSwitch())
                    telepassProfiles.setEncryptedPassword(mEdtTextPassword.getText().toString());

                telepassProfiles.setPath(mPathname);

                //数据库添加记录,如果來自科學館，則不添加進數據庫
                if (!isFromScience) {
                    //mProfile为空时说明该页面为新的用户密码输入界面
                    if( null != mProfile && StringUtil.isEmpty(mProfile.getPassword())) {
                        new TelepassProfilesDatabase(mContext).updateProfile(mProfile.getId(), telepassProfiles.getUsername(), telepassProfiles.getEncryptedPassword());
                    } else {
                        TeleformManager.getInstance().insertTeleformProfile(telepassProfiles);
                    }
                }
                ShortSoundUtil.getInstance().unlock();
                finish();
                ToastUtil.showMessageInShort(context, R.string.login_success);
                break;
            case TaskController.EVENT_TASK_FAILED:
                String errorMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, errorMsg);
                break;
            case TaskController.EVENT_TASK_ERROR:

                break;
            default:
                break;
        }
    }

    private void handleSendAuth(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                finish();
                String username = mEdtTextUsername.getText().toString();
                String passowrd = "";
                if (true == mPreferencesManager.getSingouLoginSwitch())
                    passowrd = mEdtTextPassword.getText().toString();

                //若原账号是密码为空的情况, 则进行更新, 其余的都直接添加数据
                if(null != mProfile && StringUtil.isEmpty(mProfile.getPassword()))
                    new SingouProfilesDatabase(mContext).updateProfile(mProfile.getId(), username, passowrd);
                else
                    SingouManager.getInstance().insertSingouProfile(mCurrentQr, username, passowrd);

                ShortSoundUtil.getInstance().unlock();
                ToastUtil.showMessageInShort(mContext, R.string.auth_success);
                break;
            case TaskController.EVENT_TASK_FAILED:

                break;
            case TaskController.EVENT_TASK_ERROR:
                finish();
                ToastUtil.showMessageInShort(mContext, R.string.auth_fail);
                break;
            default:
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
//        this.overridePendingTransition(R.anim.activity_close,0);
    }

    private boolean isFromSingou() {
        return Constants.SOURCE_SINGOU == mSource;
    }

    /**
     * 判断是否满足约定的"singou" username
     */
    private boolean isSingouVerified() {
        return Constants.SECURITY_USERNAME.equals(mEdtTextUsername.getText().toString());
    }

    /**
     * 弹出输入安全档案的框
     */
    private void showSecurityDialog() {
        LayoutInflater inflater = LayoutInflater.from(context);
        View dialogView = inflater.inflate(R.layout.security_profile_dialog, null);
        final EditText editText = (EditText) dialogView.findViewById(R.id.proifle_username);

        /**下面的写法能够控制dialog消失*/
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.tip_security_profile))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(dialogView)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

        final AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editText.getText().toString();
                if (!StringUtil.isEmpty(username)) {
                    if (Constants.SECURITY_USERNAME.equals(username)) {
                        mPreferencesManager.setHasSecurityProfile(true);
                        ToastUtil.showMessageInShort(mContext, R.string.tip_security_profile_success);
                    } else {
                        ToastUtil.showMessageInShort(mContext, R.string.tip_security_profile_fail);
                    }
                } else {
                    ToastUtil.showMessageInShort(mContext, R.string.tip_empty_input);
                }
                dialog.dismiss();
            }
        });
        ;

    }

    /**
     * 根據固定的ip判斷是否來自科學館
     * 並相應的更改輸入框的hint顯示的提示語
     *
     * @param strIp
     * @return
     */
    private String scienceHall(String strIp) {
        if (strIp.trim().equals("115.28.134.75")) {
            mEdtTextUsername.setHint(this.getResources().getString(R.string.tip_username));
            mEdtTextPassword.setHint(this.getResources().getString(R.string.tip_message));
            isFromScience = true;
            return this.getResources().getString(R.string.host_science_hall);
        } else
            return strIp;
    }
}